import 'dart:io';
import 'dart:isolate';
import 'dart:ui';

import 'package:calculator/pub/ScreenAdapter.dart';
import 'package:calculator/pub/config.dart';
import 'package:calculator/pub/network.dart';
import 'package:device_info/device_info.dart';
import 'package:flutter/material.dart';
import 'package:flutter_downloader/flutter_downloader.dart';
import 'package:flutter_inappbrowser/flutter_inappbrowser.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:open_file/open_file.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:url_launcher/url_launcher.dart';

class H5View extends StatefulWidget {
  final Map arguments;
  H5View({Key key, this.arguments}) : super(key: key);

  @override
  _H5ViewState createState() => _H5ViewState(this.arguments);
}

class _H5ViewState extends State<H5View> {
  Map arguments;
  _H5ViewState(this.arguments);

  InAppWebViewController webView;

  String _clientId = ''; //应用唯一id
  String _phoneType = ''; //机型
  String _osVersion = ''; //系统版本号

  String fileName = '';
  String _localPath = '';
  String downloadId;
  ReceivePort _port = ReceivePort();

  bool isApk = false;

  @override
  void initState() {
    super.initState();
    _init(); //下载 初始化
  }

  @override
  void dispose() {
    super.dispose();
  }

  //统计点击申请次数
  appBizApply(int id, int gotype) async {
    print('id === >>>>   $id');
    DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
    AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
    print('${androidInfo.androidId}');
    print('${androidInfo.device}');
    print('${androidInfo.version.release}');
    print('${androidInfo.brand}');
    setState(() {
      _clientId = '${androidInfo.androidId}';
      _phoneType = '${androidInfo.device} ${androidInfo.brand}';
      _osVersion = '${androidInfo.version.release}';
    });
    var res = await Network().post('report/appBizApply', data: {
      'appBizId': id,
      'appKey': Config.appKey,
      'clientId': _clientId,
      'phoneType': _phoneType,
      'osVersion': _osVersion,
      'goType': gotype,
    });
    int code = res['status'];
    if (code == 200) {
      print('appBizApply  ===  okokokokok');
    } else {
      print('appBizApply  ===  errrrrrrror');
    }
  }

  //打开google应用市场
  launchUrl(String id) async {
    String url = 'https://play.google.com/store/apps/details?id=$id';
    print('url === >>>>  $url');
    if (await canLaunch(url)) {
      await (launch(url));
    } else {
      Fluttertoast.showToast(
        msg: 'Open fail',
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
      );
    }
  }

  ///初始化
  Future<void> _init() async {
    // await FlutterDownloader.initialize();
    IsolateNameServer.registerPortWithName(
        _port.sendPort, 'downloader_send_port');

    _port.listen((dynamic data) {
      print('UI Isolate Callback: $data');
      String id = data[0];
      DownloadTaskStatus status = data[1];
      int progress = data[2];

      print("状态111: $status");
      print("进度111: $progress");
      print("id == downloadId: ${id == downloadId}");
      if (progress == 100) {
        print('okkookokokok........   $_localPath');
        Fluttertoast.showToast(
          msg: 'Download complete',
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
        );
        // OpenFile.open("$_localPath/app-release-${versionBean.versionCode}.apk");
        OpenFile.open("$_localPath/$fileName");
      }
    });
    //下载回调
    FlutterDownloader.registerCallback(downloadCallback);
    //保存目录
    final savedDir = Directory(_localPath);
    bool hasExisted = await savedDir.exists();
    //判断目录是否存在  不存在则创建
    if (!hasExisted) {
      savedDir.create();
    }
  }

  ///回调
  static void downloadCallback(
      String id, DownloadTaskStatus status, int progress) {
    // print('背景分离回调: 任务id ($id)  \n状态 ($status)  \n进度 ($progress)');
    final SendPort send =
        IsolateNameServer.lookupPortByName('downloader_send_port');
    send.send([id, status, progress]);
  }

  //下载apk
  downloadApk(String url) async {
    // await FlutterDownloader.initialize();
    final directory = await getExternalStorageDirectory();
    setState(() {
      _localPath = directory.path;
    });

    final taskId = await FlutterDownloader.enqueue(
      url: '$url',
      savedDir: _localPath,
      showNotification: true,
      openFileFromNotification: true,
    );
    // showProgressDialog();
    downloadId = taskId;
  }

  // 检查权限
  Future<bool> _checkPermission() async {
    // if (Theme.of(context).platform == TargetPlatform.android) {
    if (Platform.isAndroid) {
      PermissionStatus permission = await PermissionHandler()
          .checkPermissionStatus(PermissionGroup.storage);
      if (permission != PermissionStatus.granted) {
        Map<PermissionGroup, PermissionStatus> permissions =
            await PermissionHandler()
                .requestPermissions([PermissionGroup.storage]);
        if (permissions[PermissionGroup.storage] == PermissionStatus.granted) {
          return true;
        }
      } else {
        return true;
      }
    } else {
      return true;
    }
    return false;
  }

  @override
  Widget build(BuildContext context) {
    ScreenAdapter.init(context);
    return Scaffold(
      body: Container(
        color: Color(0xFFF6F6F6),
        child: Column(
          children: <Widget>[
            SizedBox(
              height: ScreenAdapter.getBarHeight(),
            ),
            Expanded(
              flex: 1,
              child: Container(
                  height: 300,
                  child: InAppWebView(
                    initialUrl: '${arguments['url']}',
                    onWebViewCreated: (InAppWebViewController controller) {
                      webView = controller;
                      webView.addJavaScriptHandler(
                          handlerName: 'toApply',
                          callback: (arg) async {
                            print('555555555555555   $arg');
                            appBizApply(arg[0]['id'], arg[0]['goType']);
                            if (arg[0]['goType'] == 1) {
                              launchUrl(arg[0]['params']);
                            } else {
                              //下载apk
                              String gourl = '${arg[0]['params']}';
                              setState(() {
                                isApk = gourl.endsWith('.apk');
                                fileName = gourl.substring(
                                    gourl.lastIndexOf('/') + 1, gourl.length);
                              });
                              if (await _checkPermission()) {
                                //是不是已apk结尾
                                if (isApk) {
                                  await downloadApk(gourl);
                                } else {
                                  Fluttertoast.showToast(
                                    msg: 'Apk format error',
                                    toastLength: Toast.LENGTH_SHORT,
                                    gravity: ToastGravity.CENTER,
                                  );
                                  return;
                                }
                              }
                            }
                          });
                    },
                    initialOptions: InAppWebViewWidgetOptions(
                        inAppWebViewOptions: InAppWebViewOptions(
                      debuggingEnabled: true,
                      javaScriptEnabled: true,
                    )),
                  )),
            ),
          ],
        ),
      ),
    );
  }
}
